import 'dart:async';

import 'package:get/get.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:simudata_display/app/data/protobuf/simu_message.pb.dart';
import 'package:simudata_display/app/services/mqtt_client_service.dart';

class ChartViewController extends GetxController {
  //TODO: Implement ChartViewController

  // ignore: non_constant_identifier_names

  late StreamSubscription<SimuMessage> subscription;

  Map<String, Map<String, List<SimuData>>> dataMap = {};

  List<String> avaliableDevices = [];

  List<SimuData> simuDatas = <SimuData>[].obs;

  final count = 0.obs;
  @override
  void onInit() {
    super.onInit();
    loadCachedData();
    MqttClientService mqttClientService = Get.find();
    subscription =
        mqttClientService.messageStream.stream.listen(onReceiveSimuMessage);
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
    subscription.cancel();
  }

  void onReceiveSimuMessage(SimuMessage message) {
    simuDatas.addAll(message.datas);
    for (var data in message.datas) {
      String sersorName = data.id.toString();
      if (dataMap.containsKey(message.name)) {
        dataMap[message.name]?.update(sersorName, (value) {
          if (value.length > 1000) {
            value.removeAt(0);
          }
          value.add(data);
          return value;
        }, ifAbsent: () => <SimuData>[data]);
      } else {
        Map<String, List<SimuData>> deviceMap = {};
        deviceMap[sersorName] = <SimuData>[data];
        dataMap[message.name] = deviceMap;
        // 添加可用设备列表
        avaliableDevices.add(message.name);
      }
    }
    update();
  }

  List<SimuData> getDeviceDatas(String deviceName) {
    List<SimuData> result = [];
    if (dataMap.containsKey(deviceName)) {
      for (var element in dataMap[deviceName]!.values) {
        result += element;
      }
    }
    return result;
  }

  void loadCachedData() {
    dataMap.clear();
    MqttClientService mqttClientService = Get.find();
    dataMap = mqttClientService.simuDataMap;
  }

  void increment() => count.value++;
}
